/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Text; 
using EXtremecode.Common;
using System.Text.RegularExpressions;
using System.Collections;
namespace EXtremecode.Utils
{
	/// <summary>
	/// Summary description for StringProcessor.
	/// </summary>
	public class StringProcessor
	{
		private static char[]s_trimedCharacterList = new char[]{' ','_',']','['}; 
		private static int s_diff=32; //'a'-'A'

		public static string Property(string str)
		{
			str=AdjustText(str);
			str=Make_LetterCapitalAfterEach_character(str,'_');  //-----Sheikh_Abdul_Wahid 
			str=str.Replace("_","");//---SheikhAbdulWahid
			return str;
		}
		public static string RelationName(string parentTable,string childTable)
		{
			
			return string.Format("{0} -> {1}",parentTable,childTable);
		}
		public static string RelationProperty(string parentTable,string childTable)
		{
			return string.Format("{0}_To_{1}",Class(parentTable),Class(childTable));
		}

		public static string Class(string str)
		{
			
			str=AdjustText(str);
			str=Make_LetterCapitalAfterEach_character(str,'_');  //-----Sheikh_Abdul_Wahid 
			str=str.Replace("_","");//---SheikhAbdulWahid
			return str;
		}
		
		public static string GetFormatedKeyValuePairs(string pairsList)
		{
			return GetFormatedKeyValuePairs(pairsList,"{0} = \"{1}\" ");
		}
		public static string GetFormatedKeyValuePairs(string pairsList,string stringFormat)
		{
			string str = pairsList;
			if(str != string.Empty)
			{
				// attributes like  name@abdulwahid|pwd@sfz
				string pattern = @"\s*(?<key>.+?)(\s*@\s*)(?<value>.+?)\s*(\||$)";
				Regex regex = new Regex(pattern);
				StringBuilder sb = new StringBuilder();
				MatchCollection matchCol=regex.Matches(str);
				foreach(Match match in matchCol)
				{
					string key = match.Groups["key"].Value.Trim();
					string keyValue = match.Groups["value"].Value.Trim();

					if(key != string.Empty)
					{
						sb.Append(
							string.Format(stringFormat,key,keyValue));
					}
				}
				str = sb.ToString();
			}
			return str ;
				
		}

		public static string ConstantNStatic(string str)
		{
			return AdjustText(str).ToUpper();
		}
		public static string DBParameter(string str)
		{
			
			return string.Format("{0}",AdjustText(str).ToLower());
		}

		public static string Variable(string str)//---sheikhAbdulWahid
		{
			str= Property(str);
			if(str.Length==0)return str;
			return ToLower(str[0]) + str.Substring(1); 
		}
		public static string FileName(string str)
		{
			str=AdjustText(str);
			str=Make_LetterCapitalAfterEach_character(str,'_');  //-----Sheikh_Abdul_Wahid 
			str=str.Replace("_","");//---SheikhAbdulWahid
			return str;
		}
		public static string Namespace(string str)
		{
			return Class(str);
		}
		public static string GivenCharecterSeparated(string str,char ch,bool bCamel)//---sheikhAbdulWahid
		{
			str=AdjustText(str);
			if(bCamel)str=Make_LetterCapitalAfterEach_character(str,'_');
    		str=str.Replace('_',ch);
			return str;
		}
		public static string Caption(string str)
		{
			return GivenCharecterSeparated(str,' ',true);
		}
		public static string LeftTrim(string str,string strTrim)
		{
			bool trimed;
			return LeftTrim(str,strTrim,out trimed);
		}
		public static string RightTrim(string str,string strTrim)
		{
			bool trimed;
			return RightTrim(str,strTrim,out trimed);
		}
		public static string LeftTrim(string str,string strTrim,out bool trimed)
		{
			trimed=true;
			if(str.IndexOf(strTrim)!=0)
			{
				trimed=false;
				return str;
			}
			return str.Substring(strTrim.Length);
		}
		public static string RightTrim(string str,string strTrim,out bool trimed)
		{
			trimed=true;
			if(str.Length < strTrim.Length || str.IndexOf(strTrim,str.Length-strTrim.Length)< 0) 
			{
				trimed=false;
				return str;
			}
			return str.Substring(0,str.Length-strTrim.Length);
		}
		private static string AdjustText(string str)//sheikh_abdul_wahid
		{
			if(IsUpper(str))
			{
				str=str.ToLower();
			}
			str=str.Replace("-","_");
			str=str.Trim(s_trimedCharacterList);
			str=str.Replace(' ','_');
			str= Add_character_BeforeEachCapitalLetter(str,'_');
			return str;
		}
		
		private static string Add_character_BeforeEachCapitalLetter(string str,char character)
		{
			StringBuilder stringBuilder=new StringBuilder(str);
			int i=1;
			while(i<stringBuilder.Length) 
			{
			
			
				char ch=stringBuilder[i];
				if(IsUpper(ch) && stringBuilder[i-1]!= character && !IsUpper(stringBuilder[i-1]) )
				{
					stringBuilder.Insert(i,character);
					i++;
				}
				i++;
			}
			return stringBuilder.ToString();
		}
		private static bool IsUpper(char ch)
		{
			return (ch >= 'A' && ch <= 'Z');  //-----(ch>=65 && ch<=90)
		}
		private static bool IsUpper(string str)
		{
			StringBuilder stringBuilder=new StringBuilder(str);
			int i=0;
			while(i<stringBuilder.Length) 
			{
			
			
				char ch=stringBuilder[i];
				if(IsLower(ch)) return false;
				i++;
			
			}
			return true;
		}
		private static bool IsLower(string str)
		{
			StringBuilder stringBuilder=new StringBuilder(str);
			int i=0;
			while(i<stringBuilder.Length) 
			{
			
			
				char ch=stringBuilder[i];
				if(IsUpper(ch)) return false;
				i++;
			
			}
			return true;
		}

		private static bool IsLower(char ch)
		{
			return (ch >= 'a' && ch <= 'z');  //-----(ch>=97 && ch<=122)
		}

		private static string Make_LetterCapitalAfterEach_character(string str,char character)
		{
			StringBuilder stringBuilder=new StringBuilder(str);
			
			
			char ch;
			bool charFound=true;

			int i=0;
			while(i<stringBuilder.Length) 
			{
			
					
				ch=stringBuilder[i];
				if(ch == character)
				{
					charFound=true;
				}
				else if(charFound)
				{
					stringBuilder[i]=ToUpper(ch);
					charFound=false;
				}
				i++;
			}
			return stringBuilder.ToString();
		}
		private static char ToUpper(char ch)
		{
			if(IsLower(ch))
			{
				ch=Convert.ToChar(Convert.ToInt16(ch)-s_diff);
				
			}
			return ch;
		}
		private static char ToLower(char ch)
		{
			if(IsUpper(ch))
			{
				ch=Convert.ToChar(Convert.ToInt16(ch)+s_diff);
			}
			return ch;
		}

		public static UCPair[] SplitStringIntoDefinedParts(string input)
		{
			ArrayList al= new ArrayList(); 
			Regex regex=new Regex(@"(?<before>(.|\t|\r|\n|\s)*?)(<!--|/\*)?<!--##(?<enclosedContent>(.|\t|\r|\n|\s)*?)(\s)*?##-->(\*/|-->)?(?<after>(.|\t|\r|\n|\s)*?)(?=((<!--|/\*)?<!--##)|\z)"
				,RegexOptions.Multiline);

			MatchCollection matchCol=regex.Matches(input.ToString());
			
			foreach(Match match in matchCol)
			{
				string before= match.Groups["before"].Value; 
				string after=match.Groups["after"].Value;
				string enclosedContent=match.Groups["enclosedContent"].Value;
				
				if(before != string.Empty)
				{
					al.Add(new UCPair("Content",before));
				}
				if(enclosedContent != string.Empty)
				{
					al.Add(new UCPair("Process",enclosedContent));
				}
				if(after != string.Empty)
				{
					al.Add(new UCPair("Content",after));
				}
				
			}

			return al.ToArray(typeof(UCPair)) as UCPair[];

		}


		public static string[] GetValuesByRegularExpression(string inputString,string pattern, string groupName)
		{
			ArrayList al =  new ArrayList();
			Regex regex = new Regex(pattern);
			MatchCollection matchCol=regex.Matches(inputString);
			foreach(Match match in matchCol)
			{
				string groupValue = match.Groups[groupName].Value.Trim();
				if(groupValue != string.Empty)
				{
					al.Add(groupValue);
				}
			}
				
			
			return al.ToArray(typeof(string)) as string[];
			
				
		}

		public static string GetValueByRegularExpression(string inputString,string pattern, string groupName)
		{
			string[] values = GetValuesByRegularExpression(inputString,pattern,groupName);

			if(values.Length >0)
			{
				return values[0];
			}
			else
			{
				return string.Empty;
			}
				
		}

        public static string GetValueFromConnetionString(string connectionString, string key)
        {
            string val = string.Empty;
            Regex regex = new Regex(string.Format(@"{0}\s*=\s*(?<key>.+?)(;|$)", key), RegexOptions.IgnoreCase);
            Match match = regex.Match(connectionString);
            if (match != null)
            {
                val = match.Groups["key"].Value;
            }

            return val;
        }



	}
}
